package com.bishe.controller;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bishe.entity.User;
import com.bishe.entity.response.R;
import com.bishe.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2024-03-04 00:02:38
 */
@CrossOrigin
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @GetMapping("/userList")
    @ApiOperation("下拉用户列表")
    public R userList() {
        List<User> list = this.userService.list();
        if (CollUtil.isNotEmpty(list)) {
            List<User> collect1 = list.stream().filter(s -> "work".equals(s.getType())).collect(Collectors.toList());
            List<Map<String, Object>> collect = collect1.stream().map(user -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", user.getId());
                map.put("name", user.getUserName());
                return map;
            }).collect(Collectors.toList());
            return R.ok(collect);
        }
        return R.ok(new HashMap<>());
    }


    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param user 查询实体
     * @return 所有数据
     */
    @GetMapping("/toPage")
    @ApiOperation("分页查询所有数据")
    public R selectAll(Page<User> page, User user) {
        return R.ok(this.userService.page(page, new QueryWrapper<>(user)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @ApiOperation("通过主键查询单条数据")
    public R selectOne(@PathVariable Serializable id) {
        return R.ok(this.userService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体对象
     * @return 新增结果
     */
    @PostMapping
    @ApiOperation("新增数据")
    public R insert(@RequestBody User user) {
        return R.ok(this.userService.save(user));
    }

    /**
     * 修改数据
     *
     * @param user 实体对象
     * @return 修改结果
     */
    @PutMapping
    @ApiOperation("修改数据")
    public R update(@RequestBody User user) {
        return R.ok(this.userService.updateById(user));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping("{id}")
    @ApiOperation("删除数据")
    public R delete(@PathVariable String id) {
        return R.ok(this.userService.removeById(id));
    }
}

